var tableElem = "LAY-home-product-list";
var tableToolsElem = "LAY-home-product-tools";
var formElem = "LAY-home-product-listform";
var formSubmitElem = "LAY-home-product-listform-submit";
var formUrl = '/home/products/listform'
var historyUrl = '/home/products/list'
var baseUrl = window.globalConfig.url_product
var searchFormElem = 'LAY-home-products-search-form'
var searchFormSubmitElem = 'LAY-home-products-search-form-submit'


layui.use(['common'], function () {
    var $ = layui.$
        , admin = layui.admin
        , table = layui.table
        , form = layui.form
        , common = layui.common;

    // 加载表单中的列表
    var loadingFormTable = (product_id) => {

        var productPhotosElemId = 'LAY-home-product-photos-list'
        var productFilesElemId = 'LAY-home-product-files-list'

        var upload = layui.upload;
        var btnEvent = (type_id) => {
            let button = $('.addFiles-' + type_id);
            let accept = parseInt(type_id) === 0 ? 'images' : 'file';
            var loadIndex = undefined
            upload.render({
                elem: button//'#ID-upload-mobile-ico-btn'
                , url: window.globalConfig.url_file
                , field: "files[]"
                , data: {
                    save_type: 1
                }
                , accept: accept
                , before: function (obj) {
                    loadIndex = layer.msg('上传中', {
                        icon: 16,
                        shade: 0.01
                    });
                }
                , done: function (res) {
                    layer.close(loadIndex)
                    let link = res.data.local_url + res.data.files[0]
                    //上传完毕
                    admin.req({
                        url: window.globalConfig.url_productFiles,
                        method: "POST",
                        data: {
                            type_id: type_id,
                            product_id: product_id,
                            link: link,
                            name: product_id + "_" + Date.now()
                        },
                        done() {
                            table.reload(parseInt(type_id) === 0 ? `${productPhotosElemId}` : `${productFilesElemId}`)
                        }
                    })
                }
            });
        }

        var toolbarEvent = (elem) => {
            table.on(`tool(${elem.id})`, function (obj) {
                var data = obj.data;
                if (obj.event === 'del') { // 删除详情
                    layer.confirm('确定删除此文件？', function (index) {
                        admin.req({
                            url: window.globalConfig.url_productFiles + "/" + data.id,
                            type: "DELETE",
                            success: function (res) {
                                common.ctmMsg(res.code, res.msg)
                                layer.close(index);
                                layui.table.reloadData(elem.id); //重载表格
                            }
                        })
                    });
                }
            });
        }

        // todo 图片管理
        table.render({
            elem: `#${productPhotosElemId}`
            , id: `${productPhotosElemId}`
            , lineStyle: 'height: 120px;'
            , url: baseUrl + "/" + product_id
            , parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data.productPhotos //解析数据列表
                };
            }
            , cols: [[
                {field: 'name', title: '图片名称', minWidth: 150, edit: 'text'}
                , {
                    field: 'link', title: '图片', align: 'center', minWidth: 250, templet: function (d) {
                        return `<img src="${window.globalConfig.img_bind_url + d.link}" style="width: 100%" />`
                    }
                }
                , {
                    field: 'is_show', title: '显示', minWidth: 80, templet: "#ID-table-product-files-is_show-switch"
                }
                , {field: 'sort', title: '排序', edit: 'text'}
                , {
                    title: '操作',
                    minWidth: 220,
                    align: 'center',
                    fixed: 'right',
                    toolbar: `#LAY-home-product-files-tools`
                }
            ]]
            , text: {none: '暂无数据！'}
            , done() {
                btnEvent(0)
                toolbarEvent(this)
            }
        });

        // todo 文件管理
        table.render({
            elem: `#${productFilesElemId}`
            , id: `${productFilesElemId}`
            , lineStyle: 'height: 120px;'
            , url: baseUrl + "/" + product_id
            , parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data.productFiles //解析数据列表
                };
            }
            , cols: [[
                {field: 'name', title: '文件名称', minWidth: 150, edit: 'text'}
                , {
                    field: 'link', title: '下载链接', align: 'center', minWidth: 250
                }
                , {
                    field: 'download_count', title: '下载次数', align: 'center', minWidth: 250
                }
                , {
                    field: 'is_show', title: '显示', minWidth: 80, templet: "#ID-table-product-files-is_show-switch"
                }
                , {field: 'sort', title: '排序', edit: 'text'}
                , {
                    title: '操作',
                    minWidth: 220,
                    align: 'center',
                    fixed: 'right',
                    toolbar: `#LAY-home-product-files-tools`
                }
            ]]
            , text: {none: '暂无数据！'}
            , done() {
                btnEvent(1)
                toolbarEvent(this)
            }
        });

        common.tableTextEditor(productPhotosElemId, window.globalConfig.url_productFiles, 'id')
        common.tableTextEditor(productFilesElemId, window.globalConfig.url_productFiles, 'id')
        common.tableSwitchEditor('product-files-is_show-status', window.globalConfig.url_productFiles)

    }

    /**
     * 主页面管理
     */
    var tableItem = table.render({
        elem: `#${tableElem}`
        , lineStyle: 'height: 80px;'
        , url: baseUrl
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'product_id', title: 'ID', maxWidth: 60, sort: true}
            , {
                field: 'cover_img', title: '封面图片', align: 'center', minWidth: 250, templet: function (d) {
                    return `<img src="${window.globalConfig.img_bind_url + d.cover_img}" style="width: 100%" />`
                }
            }
            , {field: 'name', title: '产品名称', minWidth: 150, edit: 'text'}
            , {
                field: 'productCategory_name',
                title: '产品分类',
                minWidth: 200,
                templet: "#TPL-dropdown-productCategory"
            }
            , {
                field: 'is_show', title: '显示', maxWidth: 80, templet: "#ID-table-product-is_show-switch"
            }
            , {
                field: 'is_hot', title: '热销', maxWidth: 80, templet: "#ID-table-product-is_hot-switch"
            }
            , {field: 'rewrite_url', title: '自定义URL', minWidth: 250, edit: 'text'}
            , {field: 'sort', title: '排序', edit: 'text'}
            , {title: '操作', minWidth: 280, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 15, 20, 25, 30]
        , text: {none: '暂无数据！'}
        , done() {
            common.tableDropdownEditor(this, window.globalConfig.url_productCategory, baseUrl, 'product_id', 'cate_id')

            // 加载下拉列表
            common.tableSearchDropdown(this,
                window.globalConfig.url_productCategory,
                'name',
                'id',
                'catId',
                'dropdown-type'
            );

            form.render(null, searchFormElem);
            form.on(`submit(${searchFormSubmitElem})`, function (data) {
                var field = data.field;
                tableItem.reloadData({url: baseUrl, where: field});
            })

        }
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = `${formUrl}`;
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    // 增删改查
    table.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;
        if (obj.event === "detail") {  // 查看详情


        } else if (obj.event === 'del') { // 删除详情
            layer.confirm('确定删除此产品？', function (index) {
                admin.req({
                    url: baseUrl + "/" + data.product_id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        layer.close(index);
                        tableItem.reloadData(); //重载表格
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改详情
            location.hash = `${formUrl}/product_id=` + data.product_id;
        } else if (obj.event === 'copy') {
            layer.confirm('确定复制此产品？', function (index) {
                var field = data
                field.name = field.name + "_copy"
                field.rewrite_url = field.rewrite_url + "_copy"
                delete field.disabled
                delete field.product_id
                delete field.uptime
                delete field.last_modify
                admin.req({
                    url: baseUrl,
                    type: "POST",
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            tableItem.reloadData()
                        }
                    }
                })
            });

        }
    });

    /**
     * 根据产品分类id 获取自定义字段
     * @param cat_id
     * @param product 产品信息
     */
    var setFieldsByCategory = function (cat_id, product) {
        common.ctmRequest(window.globalConfig.url_productCategory + "/" + cat_id).then(function (res) {
            var element = layui.element;
            let list = res.data.relationFields;
            let formHtml = '';
            for (let i = 0; i < list.length; i++) {
                let $fields = list[i]
                let fieldName = $fields.name;
                let fieldValue = $fields.value ?? "";
                let fieldId = $fields.id;

                // 将自定义填写的产品字段填充的文本框
                if (product['productExtFields'].length > 0) {
                    for (let j = 0; j < product['productExtFields'].length; j++) {
                        let productExtField = product['productExtFields'][j];
                        if (productExtField['pivot']['field_id'] === fieldId) {
                            fieldValue = productExtField['pivot']['value']
                            break;
                        }
                    }
                }

                // 根据数据类型生成相应的表单字段
                let inputHtml = '';
                inputHtml = `<input type="text" name="fields" data-id="${fieldId}" placeholder="请输入${fieldName}" value="${fieldValue}" class="layui-input" >`;
                // 添加表单字段到表单 HTML 中
                formHtml += `
                            <div class="layui-form-item">
                                <label class="layui-form-label">${fieldName}</label>
                                <div class="layui-input-inline" style="width: 50%">
                                    ${inputHtml}
                                </div>
                            </div>`;
            }

            // 将表单 HTML 添加到页面中
            element.tabAdd('lay-products-header', {
                title: '产品字段',
                id: new Date().getTime(), // 实际使用一般是规定好的id，这里以毫秒数模拟
                content: formHtml,
                change: false, // 是否添加完毕后即自动切换
                allowClose: false

            })
        })

    }

    /**
     * todo 添加内容tab
     * @param editors 编辑器ids
     * @param product 产品对象
     * @param fieldId 字段id
     * @param fieldName 字段名
     * @param fieldValue 字段内容
     */
    var addContentTab = (editors, product, fieldId, fieldName, fieldValue = "") => {
        var element = layui.element;
        let editorId = `editor-${fieldId}`
        let formHtml = `
                    <div class="layui-form-item">
                        <label class="layui-form-label">${fieldName}</label>
                        <div class="layui-input-inline" style="width: 100%">
                            <div id='${editorId}'></div>
                        </div>
                    </div>`;

        // 将表单 HTML 添加到页面中
        element.tabAdd('lay-products-header', {
            title: fieldName,
            id: fieldId, // 实际使用一般是规定好的id，这里以毫秒数模拟
            content: formHtml,
            change: false, // 是否添加完毕后即自动切换
            allowClose: true
        })
        // 加载富文本框
        common.editor(editorId)
        tinymce.get(editorId).on('init', function () {
            if (fieldValue) {
                tinymce.get(editorId).setContent(fieldValue)
            }
            editors.push({
                id: fieldId,
                name: fieldName,
                en_name: editorId
            });
        })

        // 删除标签前的措施
        element.on(`tabBeforeDelete(lay-products-header)`, function (data) {
            layer.confirm('确定删除此板块？', function (index) {
                let content_id = data.id; // 得到被删除的 tab 项的 ID(2.9.11+)
                let request_uri = window.globalConfig.url_productsContent + "/" + content_id
                admin.req({
                    url: request_uri,
                    type: "DELETE",
                    success: function (res) {
                        layer.close(index);
                        admin.events.refresh()
                    }
                })
            });
            if (product.product_id) {
                return false;
            } else {
                return true;
            }
        });
    }

    /**
     *  todo  动态设置产品内容
     * @param product 产品对象
     * @returns {*[]} 编辑器id集合
     */
    var setContentsByProduct = function (product) {
        let list = product.productContents
        let editors = [];
        for (let i = 0; i < list.length; i++) {
            let $fields = list[i]
            let fieldName = $fields.name;
            let fieldValue = $fields.content ?? "";
            let fieldId = $fields.id;
            addContentTab(editors, product, fieldId, fieldName, fieldValue);
        }
        return editors;

    }

    // 表单模块
    layui.data.done = function (d) {
        var remoteData = d.data
        layui.use(['form'], function () {
            form.render(null, formElem); //渲染该模板下的动态表单
            if (remoteData.productCategory) {
                $("#catName").val(remoteData.productCategory.name);
                setFieldsByCategory(remoteData.productCategory.id, remoteData);
            }

            // 加载上传插件
            common.uploader('ID-upload-product-btn', 'ID-upload-product-img', 'cover_img')

            let editors = [];
            // 动态加载产品内容
            if (remoteData.product_id) {
                editors = setContentsByProduct(remoteData)
            }

            // 加载产品分类下拉列表
            common.formDropdownEditor(
                `${window.globalConfig.url_productCategory}?all=1`,
                "catName",
                "catId",
                "catName",
                "id",
                "name"
            )

            /**
             * 拓展分类树图
             */
            let $checkedData = [];
            if (remoteData.productExtCat) {
                for (let i = 0; i < remoteData.productExtCat.length; i++) {
                    let item = remoteData.productExtCat[i];
                    $checkedData.push(item.id)
                }
            }
            common.ctmTree(
                window.globalConfig.url_productCategory + "?all=1",
                'ID-product-tree-extCat',
                'id',
                'name',
                $checkedData
            );


            // 加载表单中的列表
            loadingFormTable(remoteData.product_id)

            // 加载上传插件
            common.uploaderFile('ID-upload-download-btn', 'attachment')

            /**
             * todo 添加内容板块按钮点击
             */
            $('#addContent').click(function () {
                layer.prompt({title: '请输入板块名称', formType: 0, placeholder: "板块名称"}, function (text, index) {
                    let url = window.globalConfig.url_productsContent;
                    let $params = {
                        name: text
                    }
                    if (remoteData.product_id) {
                        $params['product_id'] = remoteData.product_id
                    }
                    common.ctmRequest(url, $params, "POST", null, true).then(res => {
                        let content_id = res.data.id
                        if (remoteData.product_id) {
                            admin.events.refresh()
                        } else {
                            addContentTab(editors, null, content_id, text)
                        }
                        layer.close(index);
                    })
                });
            })

            // 表单提交
            form.on(`submit(${formSubmitElem})`, function (data) {
                var field = data.field; //获取提交的字段
                field.is_show = field.is_show === undefined ? 0 : 1;
                field.is_hot = field.is_hot === undefined ? 0 : 1;

                if (editors.length > 0) {
                    field.content_list = [];
                    let contents = editors
                    for (let i = 0; i < contents.length; i++) {
                        field.content_list.push({
                            'id': contents[i].id,
                            'en_name': contents[i].en_name,
                            'name': contents[i].name,
                            'content': tinymce.get(contents[i].en_name).getContent()
                        });
                    }
                }

                // 产品类型必须包含在拓展分类里面
                let extCatIds = common.getCtmTreeData('ID-product-tree-extCat', 'id').split(',');
                if (extCatIds.indexOf(field.cate_id) === -1) {
                    extCatIds.push(field.cate_id);
                }
                field.extCatIds = extCatIds.join(',');


                let url = baseUrl
                let type = "POST";
                if (remoteData.product_id) {
                    url += "/" + remoteData.product_id;
                    type = "PUT"
                }
                var fields = $("input[name='fields']");
                var postFields = [];
                for (var i = 0; i < fields.length; i++) {
                    postFields.push({
                        id: $(fields[i]).data('id'),
                        value: $(fields[i]).val()
                    })
                }
                field.fields = postFields

                //提交 Ajax 成功后，关闭当前弹层并重载表格
                admin.req({
                    url: url,
                    type: type,
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            setTimeout(() => {
                                history.back()
                            }, 1000)
                        }
                    }
                })

            });
        });
    };

    // 表格文本修改
    common.tableTextEditor(tableElem, baseUrl, 'product_id')
    common.tableSwitchEditor('product-is_show-status', baseUrl)
    common.tableSwitchEditor('product-is_hot-status', baseUrl)
})